<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.projectName" placeholder="项目名称" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQuery" />
      <el-input v-model="listQuery.projectState" placeholder="项目状态" style="width: 200px;" class="filter-item" @keyup.enter.native="btnQuery" />
      <el-dropdown split-button type="primary" class="filter-item" @click="btnQuery">
        <i class="el-icon-search el-icon--left" />查询
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-zoom-out" @click.native="btnReset">重置</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button-group>
        <el-button v-permission="'purchase:project:save'" icon="el-icon-plus" type="primary" class="filter-item" @click="btnCreate">新增</el-button>
        <el-button v-permission="'purchase:project:delete'" icon="el-icon-delete" class="filter-item" @click="btnDelete()">批量删除</el-button>
        <el-button v-permission="'purchase:project:update'" type="warning" class="filter-item" @click="btnReplace()">批量替换</el-button>
      </el-button-group>
    </div>
    <el-table
      ref="multipleTable"
      :data="records"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :cell-style="{padding:'3px'}"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="项目名称" prop="projectName" align="center"><template slot-scope="scope"><span>{{ scope.row.projectName }}</span></template></el-table-column>
      <el-table-column label="项目金额（元）" prop="projectAmount" align="center"><template slot-scope="scope"><span>{{ scope.row.projectAmount }}</span></template></el-table-column>
      <el-table-column label="项目状态" prop="projectState" align="center"><template slot-scope="scope"><span>{{ scope.row.projectState }}</span></template></el-table-column>
      <el-table-column label="备注" prop="projectComment" align="center"><template slot-scope="scope"><span>{{ scope.row.projectComment }}</span></template></el-table-column>
      <el-table-column label="操作" align="center" width="120px">
        <template slot-scope="{row}">
          <el-button-group style="float: left;">
            <el-button type="text" @click.native="btnView(row)">查看</el-button>
            <el-button v-permission="'purchase:project:update'" style="margin-left: 5px" type="text" divided @click.native="btnUpdate(row)">修改</el-button>
            <el-button v-permission="'purchase:project:delete'" style="margin-left: 5px" type="text" divided @click.native="btnDelete(row.id)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :current.sync="listQuery.current"
      :size.sync="listQuery.size"
      @pagination="list"
    />

    <el-dialog title="" :visible.sync="dialogUpdateFormVisible" width="50%">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="110px">
        <el-form-item label="项目名称" prop="projectName"><el-input v-model="temp.projectName" :disabled="dialogStatus =='update'" /></el-form-item>
        <el-form-item label="项目金额" prop="projectAmount" v-if="dialogStatus =='update'"><el-input v-model="temp.projectAmount" :disabled="true" /></el-form-item>
        <el-form-item label="项目状态" prop="projectAmount"><el-input v-model="temp.projectState" /></el-form-item>
        <el-form-item label="备注" prop="projectComment"><el-input v-model="temp.projectComment" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogUpdateFormVisible = false">取消</el-button>
        <el-button icon="el-icon-check" type="primary" @click="dialogStatus =='update'?updateData():createData()">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="" :visible.sync="dialogFormVisible" width="90%">
      <el-form ref="dataForm" :rules="rules" :model="temp" :disabled="true" label-position="right" label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName"><el-input v-model="temp.projectName" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目金额" prop="projectAmount"><el-input v-model="temp.projectAmount" /></el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="projectComment"><el-input v-model="temp.projectComment" /></el-form-item>
      </el-form>
      <el-row>
        <el-button split-button type="primary" class="filter-item" style="float:right;" @click="btnExport">
          <i class="el-icon-download el-icon--left" />导出
        </el-button>
      </el-row>
      <el-table
        ref="detailTable"
        :data="orderDetail"
        :span-method="arraySpanMethod"
        border
        style="width: 100%"
      >
        <el-table-column prop="orderCode" label="审批单编号" align="center" />
        <el-table-column prop="supplierName" label="供应商" align="center" />
        <el-table-column prop="contractCode" label="合同编号" align="center" width="150px" />
        <el-table-column prop="contractState" label="合同状态" align="center" />
        <el-table-column prop="aogSituation" label="到货情况" align="center" />
        <el-table-column prop="invoice" label="发票" align="center" />
        <el-table-column prop="paymentSituation" label="付款情况" align="center">
          <template slot-scope="scope">
            <span style="white-space:pre-line">{{ scope.row.paymentSituation }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="materialName" label="设备名称" align="center" width="150px" />
        <el-table-column prop="materialSpecification" label="规格" align="center" width="100px" />
        <el-table-column prop="unitPrice" label="设备单价" align="center" width="50px" />
        <el-table-column prop="materialNum" label="采购数量" align="center" width="50px" />
        <el-table-column prop="materialTotalPrice" label="总价（元）" align="center" width="100px" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogFormVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="替换项目" width="20%" :visible.sync="replaceDialogVisible">
      <label>目标供应商 </label>
      <el-select v-model="nReplaceId" filterable placeholder="请选择">
          <el-option
                  v-for="item in projectOptions"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
          />
      </el-select>
      <span slot="footer" class="dialog-footer">
    <el-button @click="replaceDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="doReplace()">确 定</el-button>
    </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="confirmDialogVisible"
      width="30%"
    >
      <span>确定删除</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doDelete()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { getAction, putAction, postAction, deleteAction, getFileAction } from '@/api/manage'
import { Message } from 'element-ui'

export default {
  name: 'PurchaseProject',
  components: { Pagination },
  data() {
    return {
      dicts: [],
      orderCodeArr: undefined,
      contractCodeArr: undefined,
      projectNameArr: undefined,
      records: null,
      selectedRecords: [],
      total: 0,
      listQuery: {
        current: 1,
        size: 10,
        projectName: undefined,
        projectState: undefined
      },
      dialogFormVisible: false,
      dialogUpdateFormVisible: false,
      confirmDialogVisible: false,
      replaceDialogVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        projectName: '',
        projectAmount: undefined,
        projectState: '',
        projectComment: ''
      },
      orderDetail: [],
      rules: {
        id: [{ required: true, message: '该项不能为空', trigger: 'change' }],
        projectName: [{ required: true, message: '该项不能为空', trigger: 'change' }],
        projectState: [{ required: true, message: '该项不能为空', trigger: 'change' }]
      },
      deleteIds: [],
      replaceIds: [],
      projectOptions: [],
      nReplaceId: null
    }
  },
  beforeCreate() {

  },
  created() {
    this.list()
  },
  methods: {
    list() {
      getAction('/purchase/project/list', this.listQuery).then(res => {
        const { data } = res
        this.records = data.records
        this.total = data.total
      })
    },
    btnQuery() {
      this.listQuery.current = 1
      this.list()
    },
    btnReset() {
      this.listQuery = {
        current: 1,
        size: 10,
        projectName: undefined,
        projectState: undefined
      }
      this.list()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        projectName: '',
        projectState: '',
        projectComment: ''
      }
    },
    btnView(row) {
      this.temp = Object.assign({}, row)
      this.orderDetail = row.details == null ? [] : row.details
      this.merage()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    btnCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogUpdateFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          postAction('/purchase/project/save', this.temp).then(({ msg }) => {
            this.dialogUpdateFormVisible = false
            Message.success(msg)
            this.list()
          })
        }
      })
    },
    btnUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogUpdateFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          putAction('/purchase/project/update', this.temp).then(({ msg }) => {
            this.dialogUpdateFormVisible = false
            Message.success(msg)
            this.list()
          })
        }
      })
    },
    btnDelete(id) {
      const ids = id ? [id] : this.selectedRecords.map(record => {
        return record.id
      })
      if (ids.length === 0) {
        Message.error('请选择要删除的记录')
        return
      }
      this.deleteIds = ids
      this.confirmDialogVisible = true
    },
    doDelete() {
      deleteAction('/purchase/project/delete', {
        ids: this.deleteIds.toString()
      }).then(({ msg }) => {
        Message.success(msg)
        this.list()
      })
      this.confirmDialogVisible = false
    },
    selectionChange(selectedRecords) {
      this.selectedRecords = selectedRecords
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1) {
        const row1 = this.supplierNameArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 0) {
        const row1 = this.orderCodeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 2 || columnIndex === 3 || columnIndex === 4 || columnIndex === 5 || columnIndex === 6) {
        const row1 = this.contractCodeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    btnReplace() {
      const oids = this.selectedRecords.map(record => {
        return record.id
      })
      if (oids.length === 0) {
        Message.error('请选择要替换的项目')
        return
      }
      this.replaceIds = oids

      getAction('/purchase/project/listAll').then(
        res => {
          const { data } = res
          this.projectOptions = data.filter((item) => {
            return !this.replaceIds.includes(item.id)
          })
        }
      )
      this.replaceDialogVisible = true
    },
    doReplace() {
      getAction('/purchase/project/replaceProject', {
        oids: this.replaceIds.toString(), nid: this.nReplaceId
      }).then(({ msg }) => {
        Message.success(msg)
        this.list()
      })
      this.nReplaceId = null
      this.replaceDialogVisible = false
    },
    btnExport() {
      getFileAction('/purchase/project/export?projectId=' + this.temp.id).then(res => {
        if (res.type === 'application/json') {
          const reader = new FileReader() // 创建读取文件对象
          reader.addEventListener('loadend', function() { //
            const resJson = JSON.parse(reader.result) // 返回的数据
            Message.error(resJson.msg)
          })
          reader.readAsText(res, 'utf-8') // 设置读取的数据以及返回的数据类型为utf-8
        } else {
          const doca = window.document.createElement('a')
          const url = window.URL.createObjectURL(res)

          doca.href = url
          doca.setAttribute('download', this.temp.projectName + '.xls')
          window.document.body.appendChild(doca)
          doca.click()
          window.document.body.removeChild(doca)
          window.URL.revokeObjectURL(url)
        }
      })
    },
    merage() {
      this.orderCodeArr = []
      this.supplierNameArr = []
      this.contractCodeArr = []
      let orderPos = 0
      let contractPos = 0
      let supplierPos = 0
      for (let i = 0; i < this.orderDetail.length; i++) {
        if (i === 0) {
          this.orderCodeArr.push(1)
          this.supplierNameArr.push(1)
          this.contractCodeArr.push(1)
        } else {
          if (this.orderDetail[i].orderCode === this.orderDetail[i - 1].orderCode) {
            this.orderCodeArr[orderPos] += 1
            this.orderCodeArr.push(0)
          } else {
            this.orderCodeArr.push(1)
            orderPos = i
          }
          if (this.orderDetail[i].supplierName === this.orderDetail[i - 1].supplierName) {
            this.supplierNameArr[supplierPos] += 1
            this.supplierNameArr.push(0)
          } else {
            this.supplierNameArr.push(1)
            supplierPos = i
          }

          if (this.orderDetail[i].contractCode === this.orderDetail[i - 1].contractCode) {
            this.contractCodeArr[contractPos] += 1
            this.contractCodeArr.push(0)
          } else {
            this.contractCodeArr.push(1)
            contractPos = i
          }
        }
      }
    }
  }
}
</script>
